package me.lcc.demo.service.login;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import me.lcc.demo.model.Account;
import me.lcc.demo.repository.AccountRepository;

@Component("s")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	AccountRepository accountRepository;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 1. 查询用户
		Account account = accountRepository.findByUsername(username);
		if (account == null) {
			throw new UsernameNotFoundException("Account " + username + " was not found in db");
		}else if(StringUtils.isEmpty(account.getRole())) {
			throw new UsernameNotFoundException("Account " + username + " was not setter role");
		}
		
		// 2. 设置角色
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		String[] roles = account.getRole().split(",");
		for (String role : roles) {
			// 此处注意，需要在角色前面追加"ROLE_",切记切记。
			grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.trim()));
		}
		
		// 如果表里的数据带有前缀并以逗号分隔，可以直接用下面的语句。
//     List<GrantedAuthority> authorityLists = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,ROLE_USER");
		
		// 返回账户信息
		return new User(username,account.getPassword(), grantedAuthorities);
	}
}
